package com.min.oss.service;

import cn.hutool.core.io.FileUtil;
import cn.hutool.log.Log;
import com.min.oss.config.OssProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;

/**
 * 将文件存入本地文件系统
 * @author: fengt
 * @date: 2021/4/23 18:18
 **/
public class LocalService implements StorageService {

    private final Log log = Log.get();

    @Autowired
    OssProperties p;

    @Override
    public String save(InputStream is, String filename) {
        String filePath = p.getPath() + File.separator + filename;
        String fileUrl = p.getUrl() + File.separator + filename;
        try (FileOutputStream fo = new FileOutputStream(FileUtil.touch(filePath))) {
            int bytesRead = 0;
            byte[] buffer = new byte[4096];
            while ((bytesRead = is.read(buffer)) != -1) {
                fo.write(buffer, 0, bytesRead);
            }
            fo.flush();
            return fileUrl;
        } catch (FileNotFoundException e) {
            log.error("文件不存在：" + filename, e);
        } catch (IOException e) {
            log.error("文件存储异常", e);
        }

        return null;
    }

    @Override
    public boolean delete(String fileUrl) {
        try {
            String filePath = fileUrl.replace(p.getUrl(), p.getPath());
            return Files.deleteIfExists(Paths.get(filePath));
        } catch (IOException e) {
            log.error("文件" + fileUrl + "删除异常", e);
            return false;
        }
    }

}
